<?php
declare(strict_types=1);

namespace Service\GoodsService;

use Service\BaseService;
use Service\Code\Normal;
use App\Model\BbcModel\Mnuser;
use App\Model\BbcModel\CategoryBanner;
use App\Model\BbcModel\MnStoreGoods;
use App\Model\BbcModel\Goods;
use App\Model\BbcModel\GoodsClass;
use App\Model\BbcModel\GoodsBrand;
use Service\GoodsClassService\ClassService;
use Service\GoodsBrandService\BrandService;
use Service\HelperService\Common;
use Service\CacheService\CacheProviderService as Cache;

/**
 * TO C/B SBBC 商品分类
 * @author hj
 */
class GoodsClassService extends BaseService
{
    /**
     * 获取商品分类
     * @param array $param 包含了系统默认参数
     * @author: hj
     */
    public function getclass(array $param)
    {
        return ClassService::getClassTree($param['pid'], $param['cid'] ?? 0);
    }

    /**
     * 根据分类获取热门品牌和热门分类
     * @param array $param 包含了系统默认参数
     * @author: hj
     */
    public function gethot(array $param)
    {
        $class_id  = !empty($param['class_id']) ? (int)($param['class_id']) : 0;
        $cache_key = "GoodsClass_GetHot_{$class_id}";
        $data      = Cache::getCacheByKey($cache_key);
        if (empty($data)) {
            //热门分类
            $hot_class = [];
            $classRes  = ClassService::getClassChildren($class_id);
            $sub_class = $classRes['code'] == Normal::SUC ? $classRes['data'] : [];
            if (!empty($sub_class)) {
                foreach ($sub_class as &$item) {
                    $item_sub     = ClassService::getClassChildren($item['id']);
                    $item_sub     = $item_sub['code'] == Normal::SUC ? $item_sub['data'] : [];
                    $item_sub_ids = array_column($item_sub, 'id');
                    $num          = Goods::whereIn('class_id', $item_sub_ids)->selectRaw('SUM(num_sale) AS numss')->first();
                    $item['num']  = $num ? $num->num : 0;
                }
                unset($item);
            }
            array_multisort(array_column($sub_class, 'num'), SORT_DESC, $sub_class);
            for ($i = 0; $i < 6; $i++) {
                if (!empty($sub_class[$i])) {
                    array_push($hot_class, $sub_class[$i]);
                }
            }
            //热门品牌
            $hot_brand     = [];
            $sub_class_ids = array_column($sub_class, 'id');
            $brand_ids     = GoodsBrand::whereIn('class_id', $sub_class_ids)->pluck('id')->toArray();
            if (!empty($brand_ids)) {
                $list = Goods::whereIn('brand_id', $brand_ids)->orderBy('num_sale', 'desc')->limit(6)->selectRaw('DISTINCT brand_id')->get();
                if ($list->isNotEmpty()) {
                    $limit_brand_ids = $list->pluck('brand_id')->toArray();
                    $goodsbrand      = BrandService::getBrand($limit_brand_ids);
                    foreach ($list as $item) {
                        //品牌
                        $brand = $goodsbrand[$item['brand_id']] ?? [];
                        if ($brand) {
                            $hot_brand[] = $brand;
                        }
                    }
                }
            }
            $data = [
                'hot_class' => $hot_class,
                'hot_brand' => $hot_brand,
            ];
            Cache::cacheBySetKeyValue($cache_key, $data, 300);
        }
        return Normal::returnCode(Normal::SUC, '获取成功', $data);
    }

    /**
     * 获取商品分类Banner
     * @param array $param 包含了系统默认参数
     * @author: hj
     */
    public function getClassBanner(array $param)
    {
        if (!isset($param['class_id']) || empty($param['class_id']) || (preg_match("/^[1-9]\d*$/", (string)$param['class_id']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument class_id');
        }
        if (isset($param['mn_sid']) && !empty($param['class_id'])) {
            $mn_sid = (int)($param['mn_sid']);
            $cid    = Mnuser::where('id', $mn_sid)->value('pid');
        } elseif (isset($param['cid']) && !empty($param['cid'])) {
            $mn_sid = 0;
            $cid    = (int)($param['cid']);
        } else {
            return Normal::returnCode(Normal::FAIL, 'invalid argument mn_sid or cid');
        }
        $info = [];
        $id   = 0;
        if ($mn_sid != 0) {
            $id = CategoryBanner::where('class_id', $param['class_id'])->where('df', 0)->where('mn_sid', $mn_sid)->value('id');
        }
        if (empty($id)) {
            $id = CategoryBanner::where('class_id', $param['class_id'])->where('df', 0)->where('cid', $cid)->value('id');
        }
        if ($id) {
            $info = CategoryBanner::getDetail($id, false);
        }
        return Normal::returnCode(Normal::SUC, '获取成功', $info['data'] ?? []);
    }

    /**
     * 获取商品分类及商品数量
     * @param array $param 包含了系统默认参数
     * @author: hj
     */
    public function getClassNumber(array $param)
    {
        if (!isset($param['mn_sid']) || empty($param['mn_sid']) || (preg_match("/^[1-9]\d*$/", (string)$param['mn_sid']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument mn_sid');
        }
        $param['cid'] = (int)($param['cid']) ?? 0;
        $param['pid'] = (int)($param['pid']) ?? 0;
        $mn_sid       = (int)($param['mn_sid']);
        $fields       = ['id', 'name', 'icon', 'pid', 'description'];
        $classes      = GoodsClass::where('show', 1)->where('df', 0)->where('cid', $param['cid'])->where('pid', $param['pid'])->select($fields)->orderBy('sort', 'desc')->get()->toArray();
        $classes      = ClassService::tree($classes, $param['pid'], 'id', 'pid');
        $class_ids    = array_column($classes, 'id');
        $goodsClass   = MnStoreGoods::query()->from((new MnStoreGoods)->getTable() . ' as mg')->leftJoin("ly_goods as g", 'g.id', '=', 'mg.goods_id')
            ->where('mg.mn_sid', $mn_sid)->where(function ($query) {
                $query->where(function ($q) {
                    $q->where('mg.status', 1)->where('mg.df', 0);
                })->orWhere('mg.num', '>', 0);
            })->whereIn('g.class_id', $class_ids)->groupBy('g.class_id')->selectRaw('count(*) as num, g.class_id')->get()->toArray();
        $classIndex   = array_column($goodsClass, 'num', 'class_id');
        foreach ($classes as $k => $v) {
            $classes[$k]['num'] = $classIndex[$v['id']] ?? 0;
        }
        return Normal::returnCode(Normal::SUC, '获取成功', $classes);
    }

    /**
     * 获取所有二级分类
     * @param array $param 包含了系统默认参数
     * @author: hj
     */
    public function getChildrenClass(array $param)
    {
        if (!isset($param['cid']) || empty($param['cid'])) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument cid');
        }
        $cache_key     = "GoodsClass_GetChildrenClass_Channel_" . $param['cid'];
        $classChildren = Cache::getCacheByKey($cache_key);
        if (empty($classChildren)) {
            $fields        = ['id', 'name', 'icon', 'pid', 'description'];
            $classChildren = GoodsClass::where('show', 1)->where('df', 0)->where('pid', '>', 0)->where('cid', (int)($param['cid']))->select($fields)->orderBy('sort', 'desc')->get()->toArray();
            if ($classChildren) {
                foreach ($classChildren as &$item) {
                    if (!empty($item['icon']) && strpos($item['icon'], 'http') === false) {
                        $item['icon'] = Common::$pre_image_url . $item['icon'];
                    }
                }
                unset($item);
            }
            Cache::cacheBySetKeyValue($cache_key, $classChildren, 300);
        }
        return Normal::returnCode(Normal::SUC, '获取成功', $classChildren);
    }

    /**
     * 获取list
     * @param array $ids
     */
    public function getClassList( array $ids)
    {
        $son = Goodsclass::instance()->where('pid','in', $ids)->where(['df'=>0,'show'=>1])->get()->toArray();
        $fath = Goodsclass::instance()->where('id','in', $ids)->where(['df'=>0,'show'=>1])->get()->toArray();
        return array_merge($son,$fath);
    }
}